package join

import (
	"context"
	"github.com/brocaar/chirpstack-api/go/v3/gw"
	"github.com/brocaar/lorawan"
	"network/v3/internal/config"
	"network/v3/internal/models"
	"network/v3/internal/storage"
)

var (
	rxWindow               int
	downlinkTXPower        int
	gatewayPreferMinMargin float64
)

type joinContext struct {
	ctx context.Context

	Token               uint16
	DeviceSession       storage.DeviceSession
	DeviceGatewayRXInfo []storage.DeviceGatewayRXInfo
	RXPacket            models.RXPacket
	PHYPayload          lorawan.PHYPayload
	DownlinkGateway     storage.DeviceGatewayRXInfo
	DownlinkFrame       gw.DownlinkFrame
}

// Setup sets up the join handler.
func Setup(conf config.Config) error {
	nsConfig := conf.NetworkServer.NetworkSettings
	rxWindow = nsConfig.RXWindow
	downlinkTXPower = nsConfig.DownlinkTXPower
	gatewayPreferMinMargin = nsConfig.GatewayPreferMinMargin

	return nil
}

// Handle handles a downlink join-response.
func Handle(ctx context.Context, ds storage.DeviceSession, rxPacket models.RXPacket, phy lorawan.PHYPayload) error {
	joinCtx := joinContext{
		ctx:           ctx,
		DeviceSession: ds,
		PHYPayload:    phy,
		RXPacket:      rxPacket,
	}

	return HandleRunTasks(&joinCtx)
}

func HandleRunTasks(joinCtx *joinContext) error {
	for _, task := range tasks {
		if err := task(joinCtx); err != nil {
			return err
		}
	}

	return nil
}
